#!/bin/bash
#设置任务异常退出
set -eo pipefail
dt='{{ execution_date | date_add(-2) | cst_ds }}'
name='中心停留时长超36-48小时明细表'
# 在退出时清理文件
trap "rm -f /tmp/${name}_${dt}.zip /tmp/${name}_${dt}.csv && echo 'removed tmp files'" EXIT
# 创建txt文件
touch /tmp/${name}_${dt}.txt
#将中文字段名输入文件顶部
#将查询结果追加到文件中
{
  echo -e "日期\t运单编号\t任务单\t中心名称\t中心编码\t中心到达时间\t中心发件时间\t中心发车时间\t下一站名称\t下一站是否为中心\t停留时间\t">/tmp/${name}_${dt}.txt;
  spark-sql --driver-memory 8G --num-executors 10 --executor-memory 8g --executor-cores 6  --conf spark.executor.memoryOverhead=4g --conf spark.driver.maxResultSize=3g -S -e "
    select
    to_date(t.arrival_time),
    waybill_no,
    send_shipment_no,
    arrival_site,
    arrival_site_code,
    arrival_time,
    send_time,
    last_time,
    send_next_name,
    case when send_next_type=2 then '是' else '否' end next_type,
    case when send_next_type=2 then (unix_timestamp(last_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600
         else (unix_timestamp(send_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600 end diff_time
    from jms_dm.dm_center_stop_time_dt t
    where t.send_time <> '0000-0000-0000' and t.arrival_time < t.send_time  and t.dt='{{ execution_date | date_add(-2) | cst_ds }}'
    and (
            case when send_next_type=2 then (unix_timestamp(last_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600
                 else (unix_timestamp(send_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600 end >=36
         and
     case when send_next_type=2 then (unix_timestamp(last_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600
                 else (unix_timestamp(send_time) - unix_timestamp(nvl(cancal_time,arrival_time))) / 3600 end  < 48
    ) ;
 " >>/tmp/${name}_${dt}.txt
}

# 替换分隔符，并输出csv
cat /tmp/${name}_${dt}.txt | tr -s '\t' ',' > /tmp/${name}_${dt}.csv
# 压缩并删除 csv 文件
zip -jrm /tmp/${name}_${dt}.zip /tmp/${name}_${dt}.csv
# 上传文件
/usr/local/python3/bin/python3  /usr/local/airflow/dags/utils/operators/upload_oss.py ${name}/${name}_${dt}.zip /tmp/${name}_${dt}.zip
# zip 文件将在进程退出后被自动清理

#声明文件大小
data_size=$(ls -lh /tmp/${name}_${dt}.zip | awk '{print $5}')
#打印文件信息
Message="${name}_${dt}.zip 上传成功 大小: $data_size"
#配置钉钉告警
curl 'https://oapi.dingtalk.com/robot/send?access_token=816a8f35fd84432ffa6bff9d7714abc322628bb4a8ded86908550d2335aba613' \
   -H 'Content-Type: application/json' \
   -d "
  {\"msgtype\": \"text\",
    \"text\": {
        \"content\": \"监控内容:$Message\"
     }
  }" || true
rm -f  /tmp/${name}_${dt}.txt